export interface BasicUseScrollNav {
    // 导航list
    socNavList: object[],
    // 导航active
    activeSocNav: string,
    // 滚动导航容器id
    ParentId:string
}
export function useScrollNav(options: BasicUseScrollNav) {
    // 所有锚点 offset
    const offsetTopList = ref<any>([]);
    // 设置导航
    function setChangeNav(id: any) {
        options.activeSocNav = id;
    }

    // 点击切换导航
    function changeNav(id: string) {
        goAnchor(id);
    }
    // 跳转锚点
    function goAnchor(anchor: string) {
        const element: any = document.querySelector(anchor);
        scrollTo(element.offsetTop);
    }
    // 跳转锚点
    function scrollTo(offsetTop) {
        const parent = document.querySelector(options.ParentId);
        parent.scrollTo({
            top: offsetTop,
            behavior: 'smooth',
        });
    }


    // 获取所有瞄点Offset
    function geOffsetTopList() {
        let list = [];
        for (const item of options.socNavList) {
            const element: any = document.querySelector(item.id);

            list.push({
                id: item.id,
                offsetTop: element.offsetTop,
            });
        }
        offsetTopList.value = list;
    }
    // 处理滚动
    function scrollHandle({ target }) {
        const curScrollTop = target.scrollTop;
        let flag = true;
        const len = offsetTopList.value.length;
        for (let i = len - 1; i >= 0; i--) {
            const curReference = offsetTopList.value[i].offsetTop; // 当前参考值
            //console.log(curScrollTop,curReference)
            if (flag && curScrollTop >= curReference - 10) {
                flag = false;
                setChangeNav(offsetTopList.value[i].id);
            }
        }
    }
    onMounted(() => {
        setTimeout(() => {
            geOffsetTopList();
        }, 1000);

        const parent = document.querySelector(options.ParentId);
        parent.addEventListener('scroll', scrollHandle);
    });
    onBeforeUnmount(() => {
        const parent = document.querySelector(options.ParentId);
        parent.removeEventListener('scroll', scrollHandle);
    });
    return {
        changeNav
    }
}